package com.budwk.app.sqfwV2.component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.budwk.app.oss.services.SysOssService;
import com.budwk.app.sqfw.component.CommonComponent;
import com.budwk.app.sqfw.enums.SupportBusinessTypeEnum;
import com.budwk.app.sqfw.models.Sqfw_formSummary_new;
import com.budwk.app.sqfw.services.SqfwDownRecordlogService;
import com.budwk.app.sqfw.vo.GenerateExcelUrlVO;
import com.budwk.app.sqfwV2.dto.LandscapePatrolDTO;
import com.budwk.app.sqfwV2.dto.dto.dayingRoad.DownExcelLedgerReqVo;
import com.budwk.app.sqfwV2.dto.dto.dayingRoad.DownFileTypesResVo;
import com.budwk.app.sqfwV2.dto.vo.SummaryQueryReqVo;
import com.budwk.app.sqfwV2.enums.LandscapePatrolEnum;
import com.budwk.app.sqfwV2.service.SummarySafetyService;
import com.budwk.app.util.poiUtils.CommonFormOfficeUtils;
import com.budwk.app.util.poiUtils.nutzBeanUtils.NutzIocUtils;
import com.budwk.starter.common.result.Result;
import com.budwk.starter.security.utils.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.nutz.ioc.loader.annotation.IocBean;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

/**
 * 林河汛灾防治业务功能能
 */

@IocBean
@Slf4j
public class LandscapePatrolComponent {
    public static List<DownFileTypesResVo> generateFile(List<Sqfw_formSummary_new> formSummarys) {

        List<DownFileTypesResVo> list = new ArrayList<>();
        LandscapePatrolEnum[] values = LandscapePatrolEnum.values();
        for (LandscapePatrolEnum serviceEnum : values) {
            // 下载模板
            DownExcelLedgerReqVo reqVo = new DownExcelLedgerReqVo();
            reqVo.setDownTemplate(true).setFileCode(String.valueOf(serviceEnum.getCode()))
                    .setFileType(SupportBusinessTypeEnum.FOREST_AND_RIVER_FLOOD_DISASTER.getName())
                    .setDownFileType(serviceEnum.getType());
            DownFileTypesResVo resVo1 = LandscapePatrolComponent.downTemplate(reqVo);
            // 组装数据返回
            DownFileTypesResVo resVo = new DownFileTypesResVo();
            resVo.setLabel(serviceEnum.getName())
                    .setPreviewImage(List.of(serviceEnum.getPreviewImage().split(",")))
                    .setFileCode(String.valueOf(serviceEnum.getCode()))
                    .setHiveData(formSummarys.size() > 0)
                    .setFileTemplatePath(resVo1 != null ? resVo1.getFileTemplatePath() : null)
                    .setCreatedAt(System.currentTimeMillis())
                    .setLocation(serviceEnum.getCode())
                    .setFileType(serviceEnum.getType());
            buildHiveData(formSummarys, resVo, serviceEnum);
            list.add(resVo);
        }
        return list;
    }

    private static void buildHiveData(List<Sqfw_formSummary_new> formSummarys, DownFileTypesResVo resVo, LandscapePatrolEnum serviceEnum) {
        List<String> summaryIds = new ArrayList<>();
        List<String> flowIds = new ArrayList<>();
        boolean isHiveData = false; // 是否存在值
        for (Sqfw_formSummary_new formSummary : formSummarys) {
            LandscapePatrolDTO landscapePatrol = JSON.parseObject(formSummary.getParamData(), LandscapePatrolDTO.class);
            if (serviceEnum.getName().equals(landscapePatrol.getPatrolType())) {
                isHiveData = true;
                if (serviceEnum.getType().equals("pdf")) {
                    flowIds.add(formSummary.getSqfwFlowId());
                }
                if (serviceEnum.getType().equals("excel")) {
                    summaryIds.add(formSummary.getId());
                }
            }
        }
        if (serviceEnum.getType().equals("pdf")) {
            resVo.setIds(flowIds).setFileName(serviceEnum.getFileName() + ".pdf");
        }
        if (serviceEnum.getType().equals("excel")) {
            resVo.setIds(summaryIds).setFileName(serviceEnum.getFileName() + ".xlsx");
        }
        resVo.setHiveData(isHiveData);
    }

    public static DownFileTypesResVo generateDetailFile(List<Sqfw_formSummary_new> formSummarys, SummaryQueryReqVo reqVo) {
        String fileCode = reqVo.getFileCode();
        Optional<LandscapePatrolEnum> optional = Arrays.stream(LandscapePatrolEnum.values()).filter(e -> e.getCode() == Integer.parseInt(fileCode)).findFirst();
        if (optional.isPresent()) {
            LandscapePatrolEnum serviceEnum = optional.get();
            DownFileTypesResVo resVo = new DownFileTypesResVo();
            resVo.setLabel(serviceEnum.getName())
                    .setPreviewImage(List.of(serviceEnum.getPreviewImage().split(",")))
                    .setFileCode(String.valueOf(serviceEnum.getCode()))
                    .setHiveData(formSummarys.size() > 0)
                    .setCreatedAt(System.currentTimeMillis())
                    .setLocation(serviceEnum.getCode())
                    .setFileType(serviceEnum.getType());
            buildHiveData(formSummarys, resVo, serviceEnum);
            return resVo;
        }
        return new DownFileTypesResVo();
    }

    public static DownFileTypesResVo downTemplate(DownExcelLedgerReqVo reqVo) {
        LandscapePatrolEnum patrolEnum = LandscapePatrolEnum.findByCode(Integer.parseInt(reqVo.getFileCode()));
        if (patrolEnum == null) {
            return null;
        }
        if (patrolEnum.getType().equals("excel")) {
            // 属于excel模板
            SummarySafetyService summaryNewService = NutzIocUtils.getBean(SummarySafetyService.class);
            reqVo.setDownTemplate(true).setIds(new ArrayList<>());
            Result<List<GenerateExcelUrlVO>> result = summaryNewService.downloadFile(reqVo);
            // 初始数据返回
            GenerateExcelUrlVO generateExcelUrlVO = result.getData().get(0);
            DownFileTypesResVo fileTypesResVo = new DownFileTypesResVo();
            fileTypesResVo.setFileType(reqVo.getDownFileType()).setFileCode(reqVo.getFileCode()).setFileTemplatePath(generateExcelUrlVO.getExcelUrl());
            return fileTypesResVo;
        }
        if (reqVo.isAgainGenerate()) {
            return downResFile(reqVo);
        }
        // 从历史记录中获取 如果没有 则重新下载
        return downHisFile(reqVo);
    }

    private static DownFileTypesResVo downHisFile(DownExcelLedgerReqVo reqVo) {
        // 从历史任务中获取
        String filePath = LandscapePatrolEnum.getBlankTemplate(Integer.parseInt(reqVo.getFileCode()));
        String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
        // 文件标题类型 唯一性
        String title = String.format("%s%s%s", "batchDownPdfFile", fileName, SecurityUtil.getUserId());
        SqfwDownRecordlogService sqfwDownRecordlogService = NutzIocUtils.getBean(SqfwDownRecordlogService.class);
        String fileCode = reqVo.getFileCode();
        String ids = LandscapePatrolEnum.getTemplateIds(Integer.parseInt(fileCode)) + reqVo.getFileCode();
        Optional<String> optional = sqfwDownRecordlogService.getUrlByEntityIdAndTitle(ids, title);
        if (optional.isPresent()) {
            log.info("downDocTemplate filename: {}, url: {}", fileName, optional.get());
            DownFileTypesResVo fileTypesResVo = new DownFileTypesResVo();
            fileTypesResVo.setFileType(reqVo.getDownFileType()).setFileCode(reqVo.getFileCode()).setFileTemplatePath(optional.get()).setFilePath(optional.get());
            return fileTypesResVo;
        }
        // 历史记录不存在，重新下载 然后记录
        return downResFile(reqVo);
    }


    private static DownFileTypesResVo downResFile(DownExcelLedgerReqVo reqVo) {
        // 属于pdf模板
        SysOssService sysOssService = NutzIocUtils.getBean(SysOssService.class);
        String filePath = LandscapePatrolEnum.getBlankTemplate(Integer.parseInt(reqVo.getFileCode()));
        String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
        String url = sysOssService.upload(CommonFormOfficeUtils.getTempPdfFile(filePath), fileName).getUrl();
        // 组装数据返回
        DownFileTypesResVo fileTypesResVo = new DownFileTypesResVo();
        fileTypesResVo.setFileType(reqVo.getDownFileType()).setFileCode(reqVo.getFileCode()).setFileTemplatePath(url).setFilePath(url);
        // 记录下载日志
        String ids = LandscapePatrolEnum.getTemplateIds(Integer.parseInt(reqVo.getFileCode())) + reqVo.getFileCode();
        String title = String.format("%s%s%s", "batchDownPdfFile", fileName, SecurityUtil.getUserId());
        CommonComponent.insertDownRecordLog(JSONObject.toJSONString(reqVo), JSONObject.toJSONString(Result.data(url)),
                title, url, ids);
        return fileTypesResVo;
    }
}
